package com.tuling.threads.test;

/**
 * 1）互斥：两个进程同时抢占，但是口红和镜子一次只能给一个进程使用。
 * 2）占有且等待：小明进程占用了口红，但是还有镜子没有拿到；小红进程占用了镜子，但是还有口红没拿到
 * 3）不可抢占：在资源没使用完之前，不能强行抢占，比如小红还在占用镜子，小明不能强行剥夺。
 * 4）循环等待：小明想要小红的镜子，小红想要小明的口红
 *
 * @author : fujc-dev@qq.com
 * @created : 2022/5/23 16:57
 */

public class DeadLock {
    public static void main(String[] args) {
        Makeup makeup1 = new Makeup(1, "小明");
        Makeup makeup2 = new Makeup(2, "小红");
        makeup1.start();
        makeup2.start();
    }
}

class Makeup extends Thread {

    private final int choice;
    private final String name;
    private static final Lipstick lipstick = new Lipstick();
    private static final Mirror mirror = new Mirror();

    public Makeup(int choice, String name) {
        this.choice = choice;
        this.name = name;
    }

    @Override
    public void run() {
        if (this.choice == 1) {
            synchronized (lipstick) {
                System.out.println(this.name + "获得了口红");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (mirror) {
                    System.out.println(this.name + "获得了镜子");
                }
            }
        } else {
            synchronized (mirror) {
                System.out.println(this.name + "获得了镜子");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lipstick) {
                    System.out.println(this.name + "获得了口红");
                }
            }
        }
    }


    static class Lipstick {
    }

    static class Mirror {
    }
}


